package com.rzico.sbl.ui.statistic

import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityBucketBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.BucketData
import com.rzico.sbl.model.FilterData
import com.rzico.sbl.ui.member.MemberBucketActivity
import com.rzico.sbl.viewmodel.StatisticCommonViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common_ui.base.*
import com.xinnuo.common_ui.glideExt.loadCircleImage
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONObject

class BucketActivity : BaseActivity(R.layout.activity_bucket) {

    private val mBinding by lazy { ActivityBucketBinding.bind(getRootView()) }

    private val mBrandList = ArrayList<FilterData>()
    private var mKeyWord = ""
    private var mBucketType = ""
    private var mBarrelId = ""

    override fun getViewModel() = get<StatisticCommonViewModel>()

    override fun initData() {
        setToolbarVisibility(false)

        initLayout()
        initSearch()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyHint.text = "暂无相关空桶记录！"
            }

            recycleList.also { view ->
                view.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        isLoadingMore
                            .conditionFalse {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                    }
                )

                view.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                mAdapter = SlimAdapter.creator()
                    .register<BucketData>(R.layout.item_statistic_bucket) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_bucket_name, "${bean.cname}  ${bean.mobile}")
                            text(R.id.item_bucket_barrel, bean.name)
                            text(R.id.item_bucket_ya, bean.mortgage)
                            text(R.id.item_bucket_money, bean.pledge.formatDecimal())
                            text(R.id.item_bucket_borrow, bean.borrow)
                            text(R.id.item_bucket_adress, bean.address)
                            visibility(
                                R.id.item_bucket_adress,
                                goneValue { bean.address.isNullOrEmpty() }
                            )

                            with<ImageView>(R.id.item_bucket_img) {
                                it.loadCircleImage(bean.clogo, R.mipmap.default_user)
                            }

                            clicked {
                                startActivityEx<MemberBucketActivity>("cardId" to bean.cid)
                            }
                        }
                    }
                    .attachTo(view)
            }
        }
    }

    private fun initSearch() {
        mBinding
            .bucketSearch
            .apply {
                searchEdit.hint = "请输入姓名、手机号"
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        if (it.isEmpty() && mKeyWord.isNotEmpty()) {
                            mKeyWord = ""
                            updateList()
                        }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        if (searchEdit.text.isBlank()) {
                            showToast("请输入姓名、手机号")
                        } else {
                            mKeyWord = searchEdit.textTrim
                            updateList()
                        }
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    if (searchEdit.text.isBlank()) {
                        showToast("请输入姓名、手机号")
                    } else {
                        mKeyWord = searchEdit.textTrim
                        updateList()
                    }
                }
            }
    }

    override fun initListener() {
        mBinding.apply {
            bucketTypeLl.oneClick {
                getViewModel().showDropTimeFilter(
                    getIContext(),
                    bucketType,
                    bucketTypeArrow,
                    bucketTop,
                    getViewModel().mBucketTypeList
                ) {
                    if (it.id.isEmpty()) {
                        bucketType.setTextColor(getColorEx(R.color.black))
                        bucketTypeArrow.setImageResource(R.mipmap.icon_member01)
                    } else {
                        bucketType.setTextColor(getColorEx(R.color.colorAccent))
                        bucketTypeArrow.setImageResource(R.mipmap.icon_member02)
                    }

                    mBucketType = it.id

                    updateList()
                }
            }

            bucketBarrelLl.oneClick {
                if (mBrandList.isEmpty()) {
                    getBrandList { showBarrelDrop() }
                } else showBarrelDrop()
            }
        }

        getViewModel()
            .mBucketTotalEvent
            .observe(getLifecycleOwner()) {
                val obj = JSONObject(it)

                mBinding.apply {
                    when (mBucketType) {
                        "mortgage" -> {
                            layout1.visible()
                            layout2.visible()
                            layout3.gone()
                        }
                        "borrow" -> {
                            layout1.gone()
                            layout2.gone()
                            layout3.visible()
                        }
                        else -> {
                            layout1.visible()
                            layout2.visible()
                            layout3.visible()
                        }
                    }

                    bucketYa.text = obj.optNotEmpty("mortgage", "0")
                    bucketMoney.text = obj.optNotNull("pledge").formatDecimal()
                    bucketBorrow.text = obj.optNotEmpty("borrow", "0")
                }
            }
    }

    /**
     * 品牌筛选
     */
    private fun showBarrelDrop() {
        mBinding.apply {
            getViewModel()
                .showDropTimeFilter(
                    getIContext(),
                    bucketBarrel,
                    bucketBarrelArrow,
                    bucketTop,
                    mBrandList
                ) {
                    if (it.id.isEmpty()) {
                        bucketBarrel.setTextColor(getColorEx(R.color.black))
                        bucketBarrelArrow.setImageResource(R.mipmap.icon_member01)
                    } else {
                        bucketBarrel.setTextColor(getColorEx(R.color.colorAccent))
                        bucketBarrelArrow.setImageResource(R.mipmap.icon_member02)
                    }

                    mBarrelId = it.id

                    updateList()
                }
        }
    }

    /**
     * 品牌列表
     */
    private fun getBrandList(onFinish: () -> Unit) {
        getViewModel()
            .requestCommon(
                isLoading = true,
                requestUrl = BaseUrl.bucketPdt,
                requestMethod = HttpMethod.GET,
                onSuccess = { list ->
                    mBrandList.clear()
                    mBrandList.add(FilterData("全部", "", "空桶品牌", true))
                    list.mapTo(mBrandList) {
                        FilterData(
                            it.name.orEmpty(),
                            it.id,
                            it.name.orEmpty()
                        )
                    }

                    onFinish.invoke()
                }
            )
    }

    /**
     * 空桶列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        // 合计接口
        getViewModel()
            .bucketTotal(
                keyWord = mKeyWord,
                type = mBucketType,
                barrelId = mBarrelId
            )
        // 列表数据
        getViewModel()
            .bucketList(
                page = index,
                keyWord = mKeyWord,
                type = mBucketType,
                barrelId = mBarrelId,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        if (it.count() > 0) pageNum++
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}